 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=79 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:25 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Console input
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='i/o,input/output,java.io,parse,console,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Console input</div>

<div class='main-body'>
 
The 
<a href="http://java.sun.com/javase/6/docs/api/java/io/Console.html"><tt>Console</tt></a>
class allows interacting with the user in a simple textual console application. 

<P>Here is a simple example of its use :

<br>
<PRE>

<span class='keyword'>import</span> java.util.Arrays;
<span class='keyword'>import</span> java.io.Console;

<span class='comment'>/**
* Simple interactive console application.
* Uses the java.io.Console class of Java 6.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Console6 {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>void</span> main(String... aArgs){
    Console console = System.console();
    <span class='comment'>//read user name, using java.util.Formatter syntax :
</span>    String username = console.readLine(<span class='literal'>"User Name? "</span>);

    <span class='comment'>//read the password, without echoing the output 
</span>    <span class='keyword'>char</span>[] password = console.readPassword(<span class='literal'>"Password? "</span>);

    <span class='comment'>//verify user name and password using some mechanism (elided)
</span>
    <span class='comment'>//the javadoc for the Console class recommends "zeroing-out" the password 
</span>    <span class='comment'>//when finished verifying it :
</span>    Arrays.fill(password, <span class='literal'>' '</span>);

    console.printf(<span class='literal'>"Welcome, %1$s."</span>, username);
    console.printf(fNEW_LINE);

    String className = console.readLine(<span class='literal'>"Please enter a package-qualified class name : "</span>);
    Class theClass = <span class='keyword'>null</span>;
    <span class='keyword'>try</span> {
      theClass = Class.forName(className);
      console.printf(<span class='literal'>"The inheritance tree: %1$s"</span>, getInheritanceTree(theClass));
    }
    <span class='keyword'>catch</span>(ClassNotFoundException ex){
       console.printf(<span class='literal'>"Cannot find that class."</span>);
    }

    <span class='comment'>//this version just exits, without asking the user for more input
</span>    console.printf(<span class='literal'>"Bye."</span>);
  }
  
  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fHEADER = <span class='literal'>"The inheritance tree:"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fNEW_LINE = System.getProperty(<span class='literal'>"line.separator"</span>);

  <span class='keyword'>private</span> <span class='keyword'>static</span> String getInheritanceTree(Class aClass){
    StringBuilder superclasses = <span class='keyword'>new</span> StringBuilder();
    superclasses.append( fNEW_LINE );
    Class theClass = aClass;
    <span class='keyword'>while</span> ( theClass != <span class='keyword'>null</span> ) {
       superclasses.append( theClass );
       superclasses.append( fNEW_LINE );
       theClass = theClass.getSuperclass();
    }
    superclasses.append( fNEW_LINE );
    <span class='keyword'>return</span> superclasses.toString();
  }

} 
</PRE>
<br>
<p>An example run:
<p><tt>>java -cp . Console6</tt>
<pre>User Name? Leo
Password?
Welcome, Leo.
Please enter a package-qualified class name : java.util.ArrayList
The inheritance tree:
class java.util.ArrayList
class java.util.AbstractList
class java.util.AbstractCollection
class java.lang.Object

Bye.
</pre>

<P>The <tt>Console</tt> class was added in Java 6. The following is an extended example of 
using an older version of the JDK. Here, input is read from the console in a continuous loop. As well, it has 
separated the problem into several parts, such that some parts can be reused in other console applications.

<p>The user inputs a package-qualified class name, and the corresponding
inheritance tree is displayed.
<p>An example run:
<p><tt>>java -cp . Console InheritanceInterpreter</tt>
<br><tt>Please enter a class name>as;k</tt>
<br><tt>Invalid.&nbsp; Example:"java.lang.String">java.lang.String</tt>
<br><tt>The inheritance tree:</tt>
<br><tt>class java.lang.String</tt>
<br><tt>class java.lang.Object</tt>
<br><tt>Please enter a class name></tt>
<br><tt>Invalid.&nbsp; Example:"java.lang.String"></tt>
<br><tt>Invalid.&nbsp; Example:"java.lang.String">....</tt>
<br><tt>Invalid.&nbsp; Example:"java.lang.String">a;lskf</tt>
<br><tt>Invalid.&nbsp; Example:"java.lang.String">java.sql.SQLWarning</tt>
<br><tt>The inheritance tree:</tt>
<br><tt>class java.sql.SQLWarning</tt>
<br><tt>class java.sql.SQLException</tt>
<br><tt>class java.lang.Exception</tt>
<br><tt>class java.lang.Throwable</tt>
<br><tt>class java.lang.Object</tt>
<br><tt>Please enter a class name>java.util.GregorianCalendar</tt>
<br><tt>The inheritance tree:</tt>
<br><tt>class java.util.GregorianCalendar</tt>
<br><tt>class java.util.Calendar</tt>
<br><tt>class java.lang.Object</tt>
<br><tt>Please enter a class name>exit</tt>
<p><tt>Bye.</tt>
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;
<span class='keyword'>import</span> java.util.*;

<span class='comment'>/**
* Sends text back and forth between the command line and an
* Interpreter.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Console {

  <span class='comment'>/**
  * Build and launch a specific &lt;code&gt;Interpreter&lt;/code&gt;, whose
  * package-qualified name is passed in on the command line.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... aArguments) {
    <span class='keyword'>try</span> {
      Class theClass  = Class.forName(aArguments[<span class='literal'>0</span>]);
      Interpreter interpreter = (Interpreter)theClass.newInstance();
      Console console = <span class='keyword'>new</span> Console(interpreter);
      console.run();
    }
    <span class='keyword'>catch</span> ( ClassNotFoundException ex ){
      System.err.println( ex + <span class='literal'>" Interpreter class must be in class path."</span>);
    }
    <span class='keyword'>catch</span>( InstantiationException ex ){
      System.err.println( ex + <span class='literal'>" Interpreter class must be concrete."</span>);
    }
    <span class='keyword'>catch</span>( IllegalAccessException ex ){
      System.err.println( ex + <span class='literal'>" Interpreter class must have a no-arg constructor."</span>);
    }
  }

  <span class='keyword'>public</span> Console( Interpreter aInterpreter ) {
    <span class='keyword'>if</span> (aInterpreter == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Cannot be null."</span>);
    }
    fInterpreter = aInterpreter;
  }

  <span class='comment'>/**
  * Display a prompt, wait for a full line of input, and then parse
  * the input using an Interpreter.
  *
  * Exit when &lt;code&gt;Interpreter.parseInput&lt;/code&gt; returns true.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> run() {
    display( fInterpreter.getHelloPrompt() );

    <span class='comment'>//pass each line of input to fInterpreter, and display
</span>    <span class='comment'>//fInterpreter's result
</span>    InputStreamReader inputStreamReader = <span class='keyword'>new</span> InputStreamReader ( System.in );
    BufferedReader stdin = <span class='keyword'>new</span> BufferedReader ( inputStreamReader );
    <span class='keyword'>boolean</span> hasRequestedQuit = <span class='keyword'>false</span>;
    String line = <span class='keyword'>null</span>;
    List result = <span class='keyword'>new</span> ArrayList();
    <span class='keyword'>try</span> {
      <span class='keyword'>while</span> (!hasRequestedQuit) {
        line  = stdin.readLine();
        <span class='comment'>//note that "result" is passed as an "out" parameter
</span>        hasRequestedQuit = fInterpreter.parseInput( line, result );
        display( result );
        result.clear();
      }
    }
    <span class='keyword'>catch</span> ( IOException ex ) {
      System.err.println(ex);
    }
    <span class='keyword'>finally</span> {
      display(fBYE);
      shutdown( stdin );
    }
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fBYE = <span class='literal'>"Bye."</span>;
  <span class='keyword'>private</span>  Interpreter fInterpreter;

  <span class='comment'>/**
  * Display some text to stdout.
  *
  * @param aText must have a toString method.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> display( Object aText ){
    System.out.print( aText.toString() );
    System.out.flush();
  }

  <span class='comment'>/**
  * Display a List of objects as text in stdout, in the order returned
  * by the iterator of aText.
  *
  * @param aText must contain objects which have a toString method.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> display( List aText ) {
    Iterator textIter = aText.iterator();
    <span class='keyword'>while</span> ( textIter.hasNext() ) {
      display( textIter.next() );
    }
  }

  <span class='keyword'>private</span> <span class='keyword'>void</span> shutdown( Reader aStdin ){
    <span class='keyword'>try</span> {
      aStdin.close();
    }
    <span class='keyword'>catch</span> ( IOException ex ){
      System.err.println(ex);
    }
  }
} 
</PRE>
<br>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='comment'>/**
* Parse a line of text and return a result.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>interface</span> Interpreter {

  <span class='comment'>/**
  * @param aLine is non-null.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of items which all have a &lt;code&gt;toString&lt;/code&gt; method.
  *
  * @return true if the user has requested to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */</span>
  <span class='keyword'>boolean</span> parseInput (String  aLine, <span class='keyword'>final</span> List aResult);

  <span class='comment'>/**
  * Return the text to be displayed upon start-up of the Interpreter.
  */</span>
  String getHelloPrompt();
} 
</PRE>
<br>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='comment'>/**
* Given a package-qualified class name, return the names of the classes in
* the inheritance tree.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> InheritanceInterpreter <span class='keyword'>implements</span> Interpreter {

  <span class='comment'>/**
  * @param aLine is a non-null name of a class.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of class names which form the inheritance tree of the input class.
  *
  * @return true if the user has requeseted to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>boolean</span> parseInput (String  aLine, <span class='keyword'>final</span> List aResult) {
    <span class='keyword'>if</span> ( aResult == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Result param cannot be null."</span>);
    }
    <span class='keyword'>if</span> ( !aResult.isEmpty() ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Result param must be empty."</span>);
    }
    <span class='keyword'>if</span> ( aLine == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Line must not be null."</span>);
    }

    <span class='keyword'>boolean</span> hasRequestedQuit = aLine.trim().equalsIgnoreCase(fQUIT) ||
                               aLine.trim().equalsIgnoreCase(fEXIT);
    <span class='keyword'>if</span> ( hasRequestedQuit ) {
      aResult.add(fNEW_LINE);
    }
    <span class='keyword'>else</span> {
      <span class='keyword'>try</span> {
        Class theClass = Class.forName(aLine);
        StringBuilder superclasses = <span class='keyword'>new</span> StringBuilder();
        superclasses.append(fHEADER);
        superclasses.append( fNEW_LINE );
        <span class='keyword'>while</span> ( theClass != <span class='keyword'>null</span> ) {
          superclasses.append( theClass );
          superclasses.append( fNEW_LINE );
          theClass = theClass.getSuperclass();
        }
        aResult.add( superclasses );
        aResult.add( fDEFAULT_PROMPT );
      }
      <span class='keyword'>catch</span> (ClassNotFoundException ex){
        <span class='comment'>//recover by asking the user for corrected input
</span>        aResult.clear();
        aResult.add(fERROR_PROMPT);
      }
    }

    assert !aResult.isEmpty(): <span class='literal'>"Result must be non-empty."</span>;

    <span class='keyword'>return</span> hasRequestedQuit;
  }

  <span class='comment'>/**
  * Return the text to be displayed upon start-up of the Interpreter.
  */</span>
  <span class='keyword'>public</span> String getHelloPrompt() {
    <span class='keyword'>return</span> fHELLO_PROMPT;
  }

  <span class='comment'>/// PRIVATE /////
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fHELLO_PROMPT = <span class='literal'>"Please enter a class name&gt;"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fDEFAULT_PROMPT = <span class='literal'>"Please enter a class name&gt;"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fERROR_PROMPT = <span class='literal'>"Invalid.  Example:&#092;"java.lang.String&#092;"&gt;"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fHEADER = <span class='literal'>"The inheritance tree:"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fQUIT = <span class='literal'>"quit"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fEXIT = <span class='literal'>"exit"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fNEW_LINE = System.getProperty(<span class='literal'>"line.separator"</span>);
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActione704-2.html?Id=83'>Get size of object in memory</a> <br>
 
  
  <a href='TopicActionddc6-2.html?Id=113'>Construct Object using class name</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='79'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=79 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:25 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
